<script setup lang="ts">
import { getCurrentInstance, ref, watch, onBeforeMount, onMounted, onUpdated, nextTick } from 'vue'
import { onBeforeRouteLeave } from 'vue-router'
import MeScroll from 'mescroll.js'
import 'mescroll.js/mescroll.min.css'
const { proxy } = getCurrentInstance()

/* ---- */
const userInfo = proxy.$Store.get('userInfo') || {}
const logUser = proxy.$Store.get('logUser') || {}
const WXConfig = proxy.$Store.get('WXConfig') || {}

/* --设置微信分享功能-- */
proxy.$WxTool.loadJsdk(WXConfig, (obj) => {
  if (!obj) return
  // ----
  obj.hideMenuItem()
})

/* ---- */
const infoSch = ref(null)
const forSearch = ref(proxy.$Store.get('forSearch') || {})
// --mescroll--
const noData = proxy.$Global.noData
let mescroll = null
const items = ref([])

/* ---- */
const layer = ref()

/* ---- */
// --getData--
const startMeScroll = () => {
  mescroll = new MeScroll(proxy.$refs.dataScroll, {
    up: {
      callback: getListData,
      isBounce: false,
      page: { num: 0, size: 10 },
      htmlNodata: '<p class="upwarp-nodata">-- 到底啦 --</p>',
      noMoreSize: 10,
      toTop: {
        src: '/pics/mescroll-totop.png',
        offset: 1000
      },
      empty: {
        warpId: proxy.$refs.dataList,
        tip: noData
      }
    }
  })
}
const getListData = (page) => {
  getListDataFromNet({
    forUrl: 'order/index',
    forData: {
      params: {
        'OrderSearch[pro_name]': infoSch.value,
        // ----
        'OrderSearch[dealer_id]': logUser.id,
        'OrderSearch[type]': 1,
        // ----
        sort: 'SORT_DESC',
        // ----
        page: page.num,
        pageSize: page.size
      }
    }
  }, page.num, page.size, (curPageData) => {
    setListData(curPageData).then((result) => {
      mescroll.endSuccess(curPageData ? curPageData.length : 0, true)
      items.value = items.value.concat(result)
    })
  }, (resMsg) => {
    mescroll.endErr()
    proxy.$Myfun.forToast(layer.value, 'open', resMsg)
  })
}
const getListDataFromNet = (option, pageNum, pageSize, successCallback, errorCallback) => {
  if (Number(pageNum) === 1) {
    if (document.querySelector('.upwarp-nodata')) { document.querySelector('.upwarp-nodata').style.visibility = 'hidden' }
    items.value = []
  }
  // ----
  proxy.$http.get(option.forUrl, option.forData).then((res) => {
    successCallback && successCallback(res.items)
  }).catch((err) => { errorCallback && errorCallback(err) })
}
const getNeedDate = async (curItem) => {
  let forSize = []
  proxy.$Myfun.getJsonData(curItem.pro_json, (resJson) => { forSize = resJson })
  // --获取用户信息 & 商品信息 & 计量单位 & 收货地址--
  const forUserData = { params: { 'DealerSearch[id]': curItem.to_dealer_id } }
  const forGoodsData = { params: { 'ProductSearch[id]': curItem.product_id } }
  const forUnitData = { params: { 'MeasuringUnitSearch[id]': forSize[0] ? forSize[0].unit : undefined } }
  const forAddrData = { params: { 'OrderAddressSearch[order_id]': curItem.id } }
  await proxy.$Axios.all([
    proxy.$Axios.get('dealer/index', forUserData),
    proxy.$Axios.get('proc/index', forGoodsData),
    proxy.$Axios.get('measuring-unit/index', forUnitData),
    proxy.$Axios.get('order-address/index', forAddrData)
  ]).then(proxy.$Axios.spread((userData, goodsData, unitData, addrData) => {
    // --用户信息--
    if (Number(userData.items.length) > 0) {
      curItem.company = proxy.$Myfun.setText(userData.items[0].name)
      curItem.custPhone = userData.tag || userData.telphone
    }
    // --商品信息--
    if (goodsData.items && Number(goodsData.items.length) > 0) {
      const GData = goodsData.items[0]
      let forAdv = ''
      proxy.$Myfun.getJsonData(GData.img_top, (resJson) => { forAdv = resJson[0].image })
      curItem.pName = proxy.$Myfun.setText(GData.name)
      curItem.pImg = forAdv
    }
    // --计量单位--
    if (unitData.items && Number(unitData.items.length) > 0) {
      forSize.forEach((current) => { current.unit = unitData.items[0].name })
      curItem.sizes = forSize
    }
    // --收货地址--
    if (addrData.items && Number(addrData.items.length) > 0) {
      const AData = addrData.items[0]
      curItem.aName = proxy.$Myfun.setText(AData.name)
      curItem.aTelphone = AData.telphone
      curItem.aRegione = String(AData.province) === String(AData.city) ? AData.province + AData.district : AData.province + AData.city + AData.district
      curItem.aAddr = proxy.$Myfun.setText(AData.address)
    }
  })).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
}
const setListData = async (items) => {
  const newItems = []
  for (let i = 0; i < Number(items.length); i++) {
    const item = items[i]
    // ----
    const statusStyle = String(item.status) === '已签收' ? 'xw-color-1' : 'xw-color-14'
    const unitStyle = String(item.unit) === '已派发' ? 'xw-color-1' : 'xw-color-14'
    // ----
    const curItem = {
      id: item.id,
      pro_json: item.pro_json,
      to_dealer_id: item.to_dealer_id,
      product_id: item.product_id,
      // ----
      code: item.sn,
      date: proxy.$Myfun.getDateShort(item.created_at),
      totalPrice: Number(item.total_price).toFixed(2),
      status: item.status || '待签收',
      statusStyle: statusStyle,
      unit: item.unit,
      unitStyle: unitStyle,
      remark: item.remark,
      // ----
      company: '',
      custPhone: '',
      // ----
      pName: '该商品已下架！！！',
      pImg: '',
      // ----
      sizes: [],
      // ----
      aName: '',
      aTelphone: '',
      aAddr: ''
    }
    // ----
    await getNeedDate(curItem)
    // ----
    newItems.push(curItem)
  }
  return newItems
}
const divScroll = (event) => { proxy.$Myfun.setImgToTop() }
// ----
const emptyInfo = (event) => {
  const curEL = event.currentTarget
  const input = curEL.parentElement.querySelector('input')
  input.value = ''
  input.dispatchEvent(new Event('input'))
  // ----
  getHeadFun(1)
}
// ----
const getHeadFun = (type, item) => {
  switch (Number(type)) {
    case 1: {
      const newItems = []
      newItems.push(infoSch.value)
      proxy.$Myfun.setSearchRes(proxy, newItems, ['infoSch'], (result) => { forSearch.value = result })
      break
    }
  }
}
const getAuditFun = (type, item, event) => {
  switch (Number(type)) {
    case 1: {
      window.location.href = 'tel:' + item.custPhone
      break
    }
    case 2: {
      const curEL = event.currentTarget
      // ----
      proxy.$http.patch('order/update?id=' + item.id, {
        unit: curEL.value,
        // ----
        config_id: userInfo.config_id,
        openid: userInfo.openid
      }).then((res) => {
        mescroll.scrollTo(0)
        mescroll.resetUpScroll()
      }).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
      break
    }
  }
}

/* ---- */
watch(() => forSearch.value, (newVal, oldVal) => {
  infoSch.value = newVal.infoSch
  // --重新请求数据--
  mescroll.scrollTo(0)
  mescroll.resetUpScroll()
}, { deep: true })

/* ---- */
onBeforeMount(() => {
  infoSch.value = forSearch.value.infoSch
})
onMounted(() => {
  // --创建MeScroll对象--
  setTimeout(() => { startMeScroll() }, 500)
})
onUpdated(() => { nextTick(() => { proxy.$Myfun.setSectionH() }) })
onBeforeRouteLeave(() => {
  if (mescroll) mescroll.destroy()
  proxy.$Store.remove('forSearch')
})
</script>

<template>
  <div>
    <header class="xw-bg-gray">
      <div class="forTop xw-flex xw-flex-align">
        <div class="TOP-sch xw-bg-white xw-radius-3 xw-flex-W1 xw-flex xw-flex-align">
          <em class="far fa-search TOP-L"></em>
          <p class="xw-flex-W1"><input class="schText" type="text" placeholder="输入商品名称找云仓订单" v-model.trim="infoSch"/></p>
          <transition name="fade"><em class="fa fa-times-circle" @click="emptyInfo" v-if="infoSch"></em></transition>
          <span class="TOP-btn TOP-R xw-Lfg" @click="getHeadFun(1)">搜索</span>
        </div>
      </div>
    </header>
    <div class="xw-section">
      <div ref="dataScroll" class="mescroll" @scroll="divScroll">
        <ul class="list-order xw-flex xw-flex-column" ref="dataList">
          <li class="xw-bg-white xw-radius-3" v-for="(item, index) in items">
            <div class="LOD-pdt xw-flex xw-flex-align">
              <img class="LOD-pimg" :src="item.pImg" v-if="item.pImg"/>
              <div class="LOD-pname xw-flex-W1 xw-ellipsis-3">{{item.pName}}</div>
            </div>
            <div class="LOD-size xw-Tfg" v-for="(size, num) in item.sizes">
              <div><span class="xw-color-13">型号规格：</span>{{size.name}}</div>
              <div><span class="xw-color-13">订购数量：</span>{{size.num}}</div>
              <div><span class="xw-color-13">商品价格：</span>{{size.price}}元<span v-if="size.unit">/{{size.unit}}</span></div>
            </div>
            <div class="LOD-total xw-Tfg xw-flex xw-flex-align">
              <span class="xw-color-13">合计金额：</span>
              <div class="xw-color-14">{{item.totalPrice}}元</div>
            </div>
            <div class="LOD-addr xw-Tfg">
              <p><span class="xw-color-13">收货姓名：</span>{{item.aName}}</p>
              <p><span class="xw-color-13">联系电话：</span>{{item.aTelphone}}</p>
              <p><span class="xw-color-13">所属地区：</span>{{item.aRegione}}</p>
              <div class="xw-flex">
                <span class="xw-color-13">详细地址：</span>
                <div>{{item.aAddr}}</div>
              </div>
            </div>
            <div class="LOD-shop xw-Tfg">
              <div class="xw-flex">
                <span class="xw-color-13">订购商家：</span>
                <div class="xw-flex-W1 xw-color-21">{{item.company}}</div>
              </div>
              <p><span class="xw-color-13">订单编号：</span>{{item.code}}</p>
              <p><span class="xw-color-13">订购时间：</span>{{item.date}}</p>
            </div>
            <div class="LOD-desc xw-Tfg xw-flex" v-if="item.remark">
              <span class="xw-color-13">订购说明：</span>
              <div class="xw-flex-W1">{{item.remark}}</div>
            </div>
            <div class="LOD-btn xw-flex xw-flex-align xw-flex-justify">
              <span class="xw-btn xw-WBlue" @click="getAuditFun(1, item)">联系客户</span>
              <p :class="item.statusStyle">{{item.status}}</p>
              <div><select :class="['select', item.unitStyle]" @change="getAuditFun(2, item, $event)">
                <template v-if = "String(item.unit) === '已派发'">
                  <option value="待派发">待派发</option>
                  <option value="已派发" selected >已派发</option>
                </template>
                <template v-else >
                  <option value="待派发" selected >待派发</option>
                  <option value="已派发">已派发</option>
                </template>
              </select></div>
            </div>
          </li>
        </ul>
      </div>
    </div>
    <layer-view ref="layer"/>
  </div>
</template>

<style scoped>
/* ---- */
.list-order li { position: relative; margin: 1rem 1rem 0; padding: 0 1rem; overflow: hidden; }
.list-order li:nth-of-type(1) { margin-top: 0; }
.LOD-pdt { padding: 1rem 0 0; }
.LOD-pimg { margin-right: 1rem; width: 7.5rem; height: 7.5rem; }
.LOD-pname { line-height: 2.5rem; font-size: 1.7rem; }
.LOD-size { margin: 1rem 0 0; padding: 1rem 0 0; line-height: 2.5rem; }
.LOD-total { margin: 1rem 0 0; padding: 1rem 0 0; }
.LOD-total div { font-size: 1.6rem; }
.LOD-addr { margin: 1rem 0 0; padding: 1rem 0 0; line-height: 2.5rem; }
.LOD-addr span { white-space: nowrap; }
.LOD-shop { margin: 1rem 0 0; padding: 1rem 0 0; line-height: 2.5rem; }
.LOD-shop span { white-space: nowrap; }
.LOD-desc { margin: 1rem 0 0; padding: 1rem 0 0; line-height: 2.5rem; }
.LOD-btn { padding: 1rem 0 1rem; }
.LOD-btn p { font-size: 1.5rem; }
.LOD-btn div select { font-size: 1.5rem; }
</style>
